from rest_framework.generics import GenericAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from rest_framework.response import Response

from .models import ManufacturerModel
from .serializers import ManufacturerSerializer


class ManufacturerView(GenericAPIView):
    queryset = ManufacturerModel.objects.all()
    serializer_class = ManufacturerSerializer

    def get(self, request, *args, **kwargs):
        manufacturers = self.get_queryset()
        serializer = self.get_serializer(manufacturers, many=True)
        return Response(serializer.data)

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors)
        else:
            serializer.save()
            return Response(serializer.data, status=201)


class ManufacturersDetailView(GenericAPIView):
    queryset = ManufacturerModel.objects.all()
    serializer_class = ManufacturerSerializer

    def get(self, request, pk, *args, **kwargs):
        manufacturer = self.get_object()
        serializer = self.get_serializer(instance=manufacturer, many=False)
        return Response(serializer.data)

    def put(self, request, pk, *args, **kwargs):
        serializer = self.get_serializer(instance=self.get_object(), data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors)
        else:
            serializer.save()
            return Response(serializer.data)

    def delete(self, request, pk):
        self.get_object().delete()
        return Response(status=204)


class ManufacturerMinxinView(ListModelMixin, CreateModelMixin, GenericAPIView):
    queryset = ManufacturerModel.objects.all()
    serializer_class = ManufacturerSerializer

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)


class ManufacturersDetailMinxinView(RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, GenericAPIView):
    queryset = ManufacturerModel.objects.all()
    serializer_class = ManufacturerSerializer

    def get(self, request, pk):
        return self.retrieve(request, pk)

    def put(self, request, pk, *args):
        return self.update(request, pk)

    def delete(self, request, pk):
        return self.destroy(request, pk)
